import React, { Component, forwardRef } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Row,
  Col,
  Input,
  Select,
  Button,
  Table,
  Typography,
  message
} from 'antd';
import { FormInstance } from 'antd/lib/form';
import router from 'umi/router';
import Ellipsis from '../../../../components/Ellipsis';
import ExportModal from './exportModal';
import { transferOption } from '@/support/utils';

const { Title } = Typography;
const mapStateToProps = (state: any) => ({
  collectionGroupDetail: state.collectionGroupDetail,
  menu: state.menu,
  loading:  state.loading.effects['collectionGroupDetail/postFetchPage'],
});

class detailCollectionGroup extends Component<any, any> {
  formRef = React.createRef<FormInstance>();
  searchLeftRef = React.createRef<FormInstance>();
  searchRightRef = React.createRef<FormInstance>();

  state = {
    groupInfo: JSON.parse(sessionStorage.getItem('groupInfo') || '{}'), 
    dataSource: [], //穿梭框dataSource
   //左边框的数据源
    leftDataSource: [],//左边显示的数据
    rightDataSource: [],//右边显示的数据
    targetKeys: [], //targetKeys是页面右边的框,选中项集合
    selectedRowKeysLeft: [], //左边框选中的数据
    selectedRowKeysRight: [], //右边框选中的数据
    addStatus: false,//新增按钮
    removeStatus: false,//剔除按钮
    exportVisible: false,
    brandOption:[],
    seriesOption:[],
    vehicleOption:[],
    formValuesLeft: {},
    formValuesRight: {},
    seriesRightOption:[],
    vehicleRightOption:[],
  };
  componentWillMount() {
    const {groupInfo}=this.state;
    const { dispatch } = this.props;
    let params = { mode: 1, id: groupInfo.id,pageNo: 1, pageSize: 10 };
  //获取车辆池数据
    dispatch({
    type: 'collectionGroupDetail/postFetchPage',
    payload: { url: '/data/collection/vehicle/pool/list', ...params },
    callback: e =>{
      if(e.data){
        this.setState({
          leftDataSource: e.data.list
        })
      }
    }
    });
    //获取右侧实际采集车辆信息
    let param = { id: groupInfo.id};
    dispatch({
      type: 'collectionGroupDetail/postObjWithRes',
      payload: { url: '/data/collection/vehicle/view', ...param },
      callback: e =>{
        if(e.data){
          const keys: any = [];
          (e.data).map(d =>{
            keys.push(d.vin)
          })
          this.setState({
            rightDataSource: e.data,
            targetKeys: keys
          })
        }
      }
      });
       // 获取品牌数据
    this.props.dispatch({
      type: 'collectionGroupDetail/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: e => {
        this.setState({
          brandOption: e.data,
          seriesOption: [],
          vehicleOption:[]
        });
      },
    });
  }
  getBrand = ()=>{
    this.props.dispatch({
      type: 'collectionGroupDetail/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: e => {
        this.setState({
          brandOption: e.data,
          seriesOption: [],
          vehicleOption:[]
        });
      },
    });
  }
  onBrandChangeLeft = (value: any) => {
    const { dispatch } = this.props;
    this.searchLeftRef.current?.resetFields(['series']);
    if (value != null && value != undefined) {
      dispatch({
        type: 'collectionGroupDetail/getData',
        payload: { url: '/common/vehicle/getserieslist', brandId: value },
        callback: (response: any) => {
          this.setState({ seriesOption: response.data });
        },
      });
    } else {
      this.setState({ seriesOption: [] });
    }
  };
  onSeriesChangeLeft = (value: any) => {
    const { dispatch } = this.props;
    this.searchLeftRef.current?.resetFields(['vehicle']);
    const brandId = this.searchLeftRef.current?.getFieldValue('brand');
    if (value != null && value != undefined) {
      dispatch({
        type: 'collectionGroupDetail/getData',
        payload: { url: '/common/vehicle/gettypelist', brandId: brandId, seriesId: value },
        callback: (response: any) => {
          this.setState({ vehicleOption: response.data });
        },
      });
    } else {
      this.setState({ vehicleOption: [] });
    }
  };
  //左边框查询
  okForSearch1 = (values: any) => {
    const {dispatch}=this.props;
    const {groupInfo}=this.state;
    this.setState({
      formValuesLeft:values
    })
    const params ={};
    params['brand']=values.brand;
    params['series']=values.series;
    params['type']=values.type;
    params['vin']=values.vin;
    params['mode']=1;
    params['id']=groupInfo.id;
    params['pageNo']=1;
    params['pageSize']=10;
    dispatch({
      type: 'collectionGroupDetail/postFetchPage',
      payload: {url: '/data/collection/vehicle/pool/list', ...params},
      callback: e =>{
        if(e.data){
          this.setState({
            leftDataSource: e.data.list,
          })
        }
      }
      }); 
}
resetLeftForm =()=>{
  const {groupInfo}=this.state;
  this.searchLeftRef.current?.resetFields();
  this.getBrand;
  this.setState({
    seriesOption: [],
    vehicleOption: [],
    formValuesLeft: {}
  })
  let params = { mode: 1, id: groupInfo.id,pageNo: 1, pageSize: 10 };
  this.props.dispatch({
  type: 'collectionGroupDetail/postFetchPage',
  payload: {url: '/data/collection/vehicle/pool/list', ...params},
  callback: e =>{
    if(e.data){
      this.setState({
        leftDataSource: e.data.list,
      })
    }
  }
  });
}
onBrandChangeRight = (value: any) => {
  const { dispatch } = this.props;
  this.searchRightRef.current?.resetFields(['series']);
  if (value != null && value != undefined) {
    dispatch({
      type: 'collectionGroupDetail/getData',
      payload: { url: '/common/vehicle/getserieslist', brandId: value },
      callback: (response: any) => {
        this.setState({ seriesRightOption: response.data });
      },
    });
  } else {
    this.setState({ seriesRightOption: [] });
  }
};
onSeriesChangeRight = (value: any) => {
  const { dispatch } = this.props;
  this.searchRightRef.current?.resetFields(['vehicle']);
  const brandId = this.searchRightRef.current?.getFieldValue('brand');
  if (value != null && value != undefined) {
    dispatch({
      type: 'collectionGroupDetail/getData',
      payload: { url: '/common/vehicle/gettypelist', brandId: brandId, seriesId: value },
      callback: (response: any) => {
        this.setState({ vehicleRightOption: response.data });
      },
    });
  } else {
    this.setState({ vehicleRightOption: [] });
  }
};
resetRightForm =()=>{
  const{groupInfo}=this.state;
  this.searchRightRef.current?.resetFields();
  this.getBrand;
  this.setState({
    seriesOption: [],
    vehicleOption: [],
    formValuesRight: {}
  })
  let param = { id: groupInfo.id};
    this.props.dispatch({
      type: 'collectionGroupDetail/postObjWithRes',
      payload: { url: '/data/collection/vehicle/view', ...param },
      callback: e =>{
        if(e.data){
          const keys: any = [];
          (e.data).map(d =>{
            keys.push(d.vin)
          })
          this.setState({
            rightDataSource: e.data,
          })
        }
      }
      });
}
okForSearch2 = (values: any) => {
  const {dispatch}=this.props;
  const{groupInfo}=this.state;
    this.setState({
      formValuesRight:values
    })
    const params ={};
    params['brand']=values.brand;
    params['series']=values.series;
    params['type']=values.type;
    params['vin']=values.vin;
    params['id']=groupInfo.id;             
    dispatch({
      type: 'collectionGroupDetail/postObjWithRes',
      payload: {url: '/data/collection/vehicle/view', ...params},
      callback: e =>{
        if(e.data){
          this.setState({
            rightDataSource: e.data,
          })
        }
      }
      }); 
}
  handleSubmit = () =>{
    this.handleCancel
  }

  handleCancel = () => {
    sessionStorage.removeItem('groupInfo');
    router.push('/connectPlat/collectionGroup');
  };
  getData = () =>{
    const {groupInfo}=this.state;
    const { dispatch } = this.props;
    let params = { mode: 1, id: groupInfo.id,pageNo: 1, pageSize: 10 };
  //获取车辆池数据
    dispatch({
    type: 'collectionGroupDetail/postFetchPage',
    payload: { url: '/data/collection/vehicle/pool/list', ...params },
    callback: e =>{
      if(e.data){
        this.setState({
          leftDataSource: e.data.list
        })
      }
    }
    });
    //获取右侧实际采集车辆信息
    let param = { id: groupInfo.id};
    dispatch({
      type: 'collectionGroupDetail/postObjWithRes',
      payload: { url: '/data/collection/vehicle/view', ...param },
      callback: e =>{
        if(e.data){
          const keys: any = [];
          (e.data).map(d =>{
            keys.push(d.vin)
          })
          this.setState({
            rightDataSource: e.data,
            targetKeys: keys
          })
        }
      }
      });
  }  // 添加
  add = () =>{
    const {targetKeys,selectedRowKeysLeft,groupInfo}=this.state;
    const newTargetKeys = targetKeys.concat(selectedRowKeysLeft);
    
    newTargetKeys.sort();
    for(var i = 0; i< newTargetKeys.length; i++){
      if(newTargetKeys[i] == newTargetKeys[i+1]){
        newTargetKeys.splice(i,1);
        i--;
      }
    }
    this.setState({
      targetKeys: newTargetKeys,
      addStatus: false,
      selectedRowKeysLeft: [],
      selectedRowKeysRight: []
    })
    const { dispatch } = this.props;
    const name = this.formRef.current?.getFieldValue('vehicleGroupName');
    const params={id: groupInfo.id, vehicleGroupName: name, vinList: newTargetKeys, creatby: "test_connect"};
    dispatch({
      type: 'collectionGroupDetail/postObjWithRes',
      payload: { url: '/data/collection/vehicle/edit', ...params },
      callback: e =>{
       if(e.statusCode === "0"){
        message.success('添加成功')
        this.getData
       }else{
        this.getData
       }
      }
      });
  
  }
  // 剔除
  remove = () =>{
    const {targetKeys,selectedRowKeysRight,dataSource,leftDataSource,rightDataSource}=this.state;
    const newTargetKyes: any = [];
    targetKeys.map(e =>{
      if(!selectedRowKeysRight.includes(e)){
        newTargetKyes.push(e)
      }
    })
    this.setState({
      targetKeys: newTargetKyes,
      removeStatus: false,
      selectedRowKeysLeft: [],
      selectedRowKeysRight: []
    })
    const newLeftData: any = [];
    const newRightData: any = [];
    rightDataSource.map(e=>{
      if(newTargetKyes.includes(e.vin)){
        newRightData.push(e)
      }
    })
    dataSource.map(e =>{
      if(!newTargetKyes.includes(e.vin)){
        newLeftData.push(e)
      }
    })
    this.setState({
      rightDataSource: newRightData,
      leftDataSource: newLeftData
    })
  }

  handleTableChange1 = (pagination:any, filters:any) => {
    const { dispatch } = this.props;
    const { formValuesLeft, groupInfo } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      mode: 1,
      id: groupInfo.id,
      pageNo: current,
      pageSize: pageSize,
      ...formValuesLeft,
      ...filters,
    };
    dispatch({
      type: 'collectionGroupDetail/postFetchPage',
      payload: { url: '/data/collection/vehicle/pool/list', ...params },
      callback: e =>{
        if(e.data){
          this.setState({ 
            leftDataSource: e.data.list,
          })
        }
      }
    });
  };
  handleExport = (record:any) =>{
    this.setState({
      exportVisible: true,
    })
  }
  closeModal = () => {
    this.setState({
      exportVisible: false,
    })
  }
  render() {
    const {collectionGroupDetail: { pageData: { list, pagination }, }, loading, location: { pathname = '/' },menu: { permissions },} = this.props;
    const {selectedRowKeysLeft,selectedRowKeysRight,addStatus,removeStatus,leftDataSource,rightDataSource,exportVisible,
      brandOption,seriesOption,vehicleOption,seriesRightOption,vehicleRightOption}= this.state;
  const onSelectChangeLeft = (newSelectedRowKeys:any) => {
    this.setState({
      selectedRowKeysLeft: newSelectedRowKeys,
      addStatus: newSelectedRowKeys.length > 0
    })
  };
  const rowSelectionLeft = {
    selectedRowKeysLeft,
    // preserveSelectedRowKeys: true,
    onChange: onSelectChangeLeft,
  };
  const onSelectChangeRight = (newSelectedRowKeys:any) => {
    this.setState({
      selectedRowKeysRight: newSelectedRowKeys,
      removeStatus: newSelectedRowKeys.length > 0
    })
  };
  const rowSelectionRight = {
    selectedRowKeysRight,
    onChange: onSelectChangeRight,
  };                                                                                       
  const leftColumns = [
    {
      title: 'VIN',
      dataIndex: 'vin',
      key: 'vin',
      render: val => (
        <Ellipsis length={10} tooltip>{val}</Ellipsis>
      ),
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      key: 'brandName',
      render: val => (
        <Ellipsis length={10} tooltip>{val}</Ellipsis>
      ),
    },
    {
      title: '车系',
      dataIndex: 'seriesName',
      key: 'seriesName',
      render: val => (
        <Ellipsis length={10} tooltip>{val}</Ellipsis>
      ),
    },
    {
      title: '车型',
      dataIndex: 'typeName',
      key: 'typeName',
      render: val => (
        <Ellipsis length={8} tooltip>{val}</Ellipsis>
      ),
    },
    {
      title: '备注',
      dataIndex: 'mark',
      key: 'mark',
      render: val => (
        <Ellipsis length={6} tooltip>{val}</Ellipsis>
      ),
    },
  ];
    const paginationProps1 = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    return (
      <div>
        <Card bordered={false}>
            <Form
                layout="vertical"
                ref={this.formRef}
                onFinish={this.ok}
                >
                 <Form.Item label="采集车辆组名称："  required>
                   <Form.Item name="vehicleGroupName" 
                    noStyle 
                    rules={[{ required: true, message: '请输入采集车辆组名称' }]}
                    initialValue={this.state.groupInfo.vehicleGroupName}
                   >
                    <Input  placeholder="请输入采集车辆组名称" style={{width: '50%'}} disabled/>
                   </Form.Item>
                   <span
                   className="ant-form-text"
                   style={{
                       marginLeft: 8,
                    color: "rgba(0, 0, 0, 0.45)",
                   }}
                   >
                  不可重复
                    </span>
                 </Form.Item>   
                 <Form.Item  label="选择车辆："  required>
                </Form.Item>
                </Form>                                      
                   <Row gutter={24}>
                     <Col span={11}>
                        <>
                          <Row style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Title level={4} style={{textAlign: 'center'}}>{'编辑车辆池（'+(pagination.total? pagination.total : 0)+'台）'}</Title>
                          </Row>
                          <Row>
                             <Card style={{width: '100%'}}>
                               <>
                               <Card bordered={false}>
                                <Form
                                     labelCol={{
                                      span: 6,
                                    }}
                                    wrapperCol={{
                                      span: 18,
                                    }}
                                    layout="horizontal"
                                    onFinish={this. okForSearch1}
                                    ref={this.searchLeftRef}
                                   >
                                   <Row gutter={24}>
                                     <Col span={12}>
                                       <Form.Item label="品牌" name="brand">
                                       <Select
                                         showSearch
                                         placeholder="请选择"
                                         allowClear
                                         style={{width: '80%'}}
                                         optionFilterProp="children"
                                         getPopupContainer={triggerNode => triggerNode.parentNode}
                                         onChange={this.onBrandChangeLeft}
                                         >
                                           {transferOption(brandOption, ['brandCode', 'brandName'])}
                                         </Select>
                                       </Form.Item>
                                    </Col>
                                     <Col span={12}>
                                     <Form.Item label="车系" name="series">
                                     <Select
                                         showSearch
                                         placeholder="请选择"
                                         allowClear
                                         style={{width: '80%'}}
                                         optionFilterProp="children"
                                         getPopupContainer={triggerNode => triggerNode.parentNode}
                                         onChange={this.onSeriesChangeLeft}
                                         >
                                          {transferOption(seriesOption, ['code', 'name'])}
                                         </Select>
                                       </Form.Item>
                                     </Col>
                                  </Row>
                                  <Row gutter={24}>
                                     <Col span={12}>
                                     <Form.Item label="车型" name="type">
                                     <Select
                                         showSearch
                                         placeholder="请选择"
                                         allowClear
                                         style={{width: '80%'}}
                                         optionFilterProp="children"
                                         getPopupContainer={triggerNode => triggerNode.parentNode}
                                         >
                                           {transferOption(vehicleOption, ['code', 'name'])}
                                         </Select>
                                       </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                     <Form.Item label="VIN" name="vin">
                                         <Input style={{width: '80%'}}/>
                                       </Form.Item>
                                    </Col>
                                  </Row>
                                  <Row gutter={24}>
                                  <Col span={5}>
                                  </Col>
                                  <Col span={19}>
                                      <div style={{float: 'right'}}>
                                       <Button type="primary" htmlType="submit">查询</Button>
                                       <Button style={{ marginLeft: 8 }} onClick={this.resetLeftForm}>重置</Button>
                                       </div>
                                  </Col>
                                  </Row>
                                </Form>
                                 </Card>
                                   </>
                                 <Table
                                // loading={loading}
                                columns={leftColumns}
                                dataSource={leftDataSource}
                                rowKey={record => record.vin}
                                scroll={{ x: 'max-content' }}
                                size='small'
                                bordered={false}
                                rowSelection={rowSelectionLeft}
                                pagination={paginationProps1}
                                onChange={this.handleTableChange1}
                                 />
                             </Card>
                            </Row>
                        </>
                     </Col>
                     <Col span={2}>
                        <div style={{marginTop: 400}}>
                        <Button type="primary" style={{margin: 5}} shape="round" disabled onClick={this.add}>{'>'}新增</Button>
                        <Button type="primary" style={{margin: 5}} shape="round" disabled onClick={this.remove}>{'<'}剔除</Button>
                        </div>
                     </Col>
                     <Col span={11}>
                     <>
                        <Row style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                           <Title level={4} style={{textAlign: 'center'}}>{'采集车辆（'+ rightDataSource.length + '台）'}</Title>
                        </Row>
                        <Row>
                           <Card style={{width: '100%'}}>
                               <>
                               <Card bordered={false} >
                                <Form
                                     labelCol={{
                                      span: 6,
                                    }}
                                    wrapperCol={{
                                      span: 18,
                                    }}
                                    layout="horizontal"
                                    onFinish={this. okForSearch2}
                                    ref={this.searchRightRef}
                                   >
                                   <Row gutter={24}>
                                     <Col span={12}>
                                       <Form.Item label="品牌" name="brand">
                                       <Select
                                         showSearch
                                         placeholder="请选择"
                                         allowClear
                                         style={{width: '80%'}}
                                         optionFilterProp="children"
                                         getPopupContainer={triggerNode => triggerNode.parentNode}
                                         onChange={this.onBrandChangeRight}
                                         >
                                           {transferOption(brandOption, ['brandCode', 'brandName'])}
                                         </Select>
                                       </Form.Item>
                                    </Col>
                                     <Col span={12}>
                                     <Form.Item label="车系" name="series">
                                     <Select
                                         showSearch
                                         placeholder="请选择"
                                         allowClear
                                         style={{width: '80%'}}
                                         optionFilterProp="children"
                                         getPopupContainer={triggerNode => triggerNode.parentNode}
                                         onChange={this.onSeriesChangeRight}
                                         >
                                          {transferOption(seriesRightOption, ['code', 'name'])}
                                         </Select>
                                       </Form.Item>
                                     </Col>
                                  </Row>
                                  <Row gutter={24}>
                                     <Col span={12}>
                                     <Form.Item label="车型" name="type">
                                     <Select
                                         showSearch
                                         placeholder="请选择"
                                         allowClear
                                         style={{width: '80%'}}
                                         optionFilterProp="children"
                                         getPopupContainer={triggerNode => triggerNode.parentNode}
                                         >
                                           {transferOption(vehicleRightOption, ['code', 'name'])}
                                         </Select>
                                       </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                     <Form.Item label="VIN" name="vin">
                                         <Input style={{width: '80%'}}/>
                                       </Form.Item>
                                    </Col>
                                  </Row>
                                  <Row gutter={24}>
                                    <Col span={5}>
                                       <Button type="primary" onClick={this.handleExport}>批量导入</Button>
                                    </Col>
                                    <Col span={19}>
                                      <div style={{float: 'right'}}>
                                       <Button type="primary" htmlType="submit">查询</Button>
                                       <Button style={{ marginLeft: 8 }} onClick={this.resetRightForm}>重置</Button>
                                      </div>
                                  </Col>
                                </Row>
                                </Form>
                                 </Card>
                                   </>
                                 <Table
                                // loading={loading}
                                columns={leftColumns}
                                dataSource={rightDataSource}
                                rowKey={record => record.vin}
                                scroll={{ x: 'max-content', y: 300}}
                                size='small'
                                bordered={false}
                                rowSelection={rowSelectionRight}
                                pagination={false}
                                 />
                             </Card>
                            </Row>
                        </>
                     </Col>
                   </Row>
        </Card>
        <Card bordered={false}>
          <>
              {/* <Button
                type="primary"
                onClick={this.handleSubmit}
              >
                保存
              </Button> */}
            <Button htmlType="button" style={{ margin: '0 8px' }} onClick={this.handleCancel}>
              取消
            </Button>
          </>
        </Card>
        <ExportModal
          onRef={(val: any) => this.exportForm = val}
          modalVisible={exportVisible}
          closeModal={this.closeModal}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(detailCollectionGroup);
